package com.cx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;

/**
 * 授权服务器的配置类
 * Author:CHENXIAOYI
 * Since:2020/12/28 16:07
 */
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    //注入redis的连接工厂
    private final RedisConnectionFactory redisConnectionFactory;

    @Resource
    @Lazy
    private  PasswordEncoder passwordEncoder;


    public AuthorizationConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }


    /**
     * 创建一个redis的tokenStore存放颁发的token
     */
    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    /**
     *  第三方应用的配置，只有配置了第三方应用，才能访问授权服务器
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //创建一个基本的第三方应用，第三方应用少的时候，就放在内存中，多的就使用jdbc
        clients.inMemory()
                //创建一个web第三方
                .withClient("web")
                //密码
                .secret(passwordEncoder.encode("web-secret") )
                //作用域
                .scopes("web-scopes")
                //授权模式 1-验证码授权 2-密码授权 3-静默授权 4-客户端授权
                .authorizedGrantTypes("authorization_code")
                //访问成功后调整
                .redirectUris("https://www.baidu.com")
                //设置授权token的过期时间
                .accessTokenValiditySeconds(3600);
        super.configure(clients);
    }


    /**
     * token的存储方式 我们先存在redis里面
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore());
        super.configure(endpoints);
    }
}
